<?php

namespace app\admin\service;


use app\admin\validate\AuthRule;
use app\admin\model\AuthRule as AuthRuleModel;
use app\common\service\BaseAdminService;
use auth\Auth;
use think\exception\ValidateException;

class AuthRuleService extends BaseAdminService
{

    protected static $sceneLabel = [
        'add' => '权限添加',
        'edit' => '权限编辑'
    ];

    /**
     * 添加/编辑权限
     * @param $data
     * @param string $scene
     * @return array|string
     */
    public static function storeRule($data,$scene='add'){
        $data['state'] = isset( $data['state'])? $data['state']:0;
        try {
            validate(AuthRule::class)->scene($scene)->check($data);
        } catch (ValidateException $e) {
            return self::error($e->getError(),null, ['token'=>request()->buildToken()]);
        }
        $model = new AuthRuleModel();
        if ($scene !='add') {
            $result = $model->exists(true)->update($data);
        } else {
            $result = $model->create($data);
        }
        return self::getSceneMessage($result,$scene);
    }

    /**
     * 获得所有菜单选择数据
     * @return array
     */
    public static function allMenu(){
        $allMenu = AuthRuleModel::where('menu',1)->where('state',1)->field('id,title,pid as parentId')->order(['sort'=>'asc','id'=>'asc'])->select()->toArray();
        return $allMenu;
    }


    /**
     * 权限列表
     * @param bool $check
     * @return array
     */
    public static  function access($check = true){
        $tree = AuthRuleModel::where('state',1)->field('id,title,pid as parentId')->order(['sort'=>'asc','id'=>'asc'])->select()->toArray();

        //是否有复选框
        if ($check){
            foreach ($tree as &$item){
                $item['checkArr'] = '0';
            }
        }

        return $tree;
    }

    /**
     * 权限菜单
     * @param $uid
     * @param bool $to_array 是否返回数组
     * @return array
     */
    public static function authMenu($uid){
        //读取用户所属用户组
        $groups = Auth::instance()->getGroups($uid);
        $ids = []; //保存用户所属用户组设置的所有权限规则id
        foreach ($groups as $g) {
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        $ids = array_unique($ids);

        //将一级菜单查询出来
        $data = AuthRuleModel::field('id,name as href,title,menu_icon as icon,target')
            ->where('state',1)
            ->where('menu',1)
            ->where('id','in',$ids)
            ->where('pid',0)
            ->order(['sort'=>'asc','id'=>'asc'])
            ->select()
            ->toArray();

        //将href加/
        $data =  array_map(function ($v){
            $href = explode('/', $v['href']);
            $v['href'] = count($href)>1?'/'.$v['href']:'';
            return $v;
        },$data);

        $lists = self::channelLevel($ids,$data);

        return $lists;
    }

    /**
     * 返回多层栏目
     * @param $ids 权限id
     * @param array $data 上级数组
     * @return array 树形结构数据
     */
    public static  function channelLevel($ids, $data=[]){
        foreach ($data as &$item){
            $child_arr = AuthRuleModel::field('id,name as href,title,menu_icon as icon,target')
                ->where('state',1)
                ->where('menu',1)
                ->where('id','in',$ids)
                ->where('pid',$item['id'])
                ->order(['sort'=>'asc','id'=>'asc'])
                ->select();
            if ($child_arr){
                //将href加/
                $data_c =  array_map(function ($v){
                    $href = explode('/', $v['href']);
                    $v['href'] = count($href)>1?'/'.$v['href']:'';
                    return $v;
                },$child_arr->toArray());
                $item['child'] =self::channelLevel($ids, $data_c);
            }
        }
        return  $data;
    }

    /**
     * 返回此用户的所有权限菜单
     * @param $uid
     * @return mixed
     */
    public static function authAllMenu($uid){
        $admin_home = config('login_admin.admin_home');

        //控制台home
        $menu['homeInfo'] = [
            'title'=>$admin_home['title'] ,
            'href'=> '/'.app('http')->getName().'/'.$admin_home['href']
        ];

        //后台logo标题
        $logo = SysConfig('site.image');
        $menu['logoInfo'] = [
            'title'=> SysConfig('site.admin_name'),
            'image' => $logo?:'/static/admin/images/logo.png',
            'href'=> '/'
        ];
        $menu['menuInfo'] = self::authMenu($uid);
        return $menu;
    }
}
